package com.desin.modle.multithread;


import java.util.Vector;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class CountDownLatchAndCyclicBarrier {

    // 订单队列
    Vector<String> pos = new Vector<>();
    // 派送单队列
    Vector<String> dos = new Vector<>();
    // 执行回调的线程池
    Executor executor =
            Executors.newFixedThreadPool(1);
    final CyclicBarrier barrier =
            new CyclicBarrier(2, ()->{
//                check();
                executor.execute(()->check());
            });

    void check(){
        String p = pos.remove(0);
        String d = dos.remove(0);
        // 执行对账操作
        String diff = check(p, d);
        // 差异写入差异库
        save(diff);
    }

    private String check(String p, String d) {
        return p+d;
    }

    private void save(String diff) {
        System.out.println(diff);
    }

    void checkAll(){
        // 循环查询订单库
        Thread T1 = new Thread(()->{
            Integer a = 0;
            while(a<10){
                // 查询订单库
                pos.add(a+"");
                a++;
                // 减1并等待
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        T1.start();
        // 循环查询运单库
        Thread T2 = new Thread(()->{
            Integer a = 0;
            while(a<10){
                // 查询运单库
                dos.add(a+"");
                a++;
                // 减1并等待
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
        T2.start();
    }


}
